package com.example.demo.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.dao.mapper.AccountMapper;
import com.example.demo.entity.Account;
import com.example.demo.enums.DataEnum;
import com.example.demo.service.AccountService;
import com.example.demo.util.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Maps;
import org.apache.http.*;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.DateUtils;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.HttpHostConnectException;
import org.apache.http.cookie.Cookie;
import org.apache.http.cookie.CookieOrigin;
import org.apache.http.cookie.MalformedCookieException;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.cookie.DefaultCookieSpec;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.SocketTimeoutException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 账号表(Account)表服务实现类
 *
 * @author makejava
 * @since 2020-12-09 00:39:56
 */
@Service("accountService")
public class AccountServiceImpl implements AccountService {

    private final static String UA = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.87 Safari/537.36 SLBrowser/6.0.1.9171";
    private final static String UA1 = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36 Edg/87.0.664.57";

    private int ERROR_COUNT = 0;
    private int SUCCESS_COUNT = 0;

//    private String PROXY_IP;
//    private int PROXY_PORT;

    /**
     * 服务对象
     */
    @Resource
    private AccountMapper accountMapper;

    /**
     * 保存数据
     *
     * @param userId  用户ID
     * @param account 实例对象
     * @return 是否成功
     */
    @Override
    public int save(Integer userId, Account account) {
        if (account.getId() == null) {
            return insert(userId, account);
        } else {
            return update(userId, account);
        }
    }

    /**
     * 新增数据
     *
     * @param userId  用户ID
     * @param account 实例对象
     * @return 是否成功
     */
    @Override
    public int insert(Integer userId, Account account) {
        return accountMapper.insertSelective(account);
    }

    /**
     * 通过主键删除数据
     *
     * @param userId 用户ID
     * @param id     主键
     * @return 是否成功
     */
    @Override
    public int delete(Integer userId, Integer id) {
        Account account = accountMapper.selectByPrimaryKey(id);
        account.setFlag(DataEnum.FLAG_STATUS_INVALID.getCode());
        return accountMapper.updateByPrimaryKeySelective(account);
    }

    /**
     * 修改数据
     *
     * @param account 实例对象
     * @return 是否成功
     */
    @Override
    public int update(Integer userId, Account account) {
        Account a = accountMapper.selectByPrimaryKey(account.getId());
        // FIXME 待完善
        return accountMapper.updateByPrimaryKeySelective(a);
    }

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public Account queryById(Integer id) {
        return accountMapper.selectByPrimaryKey(id);
    }

    /**
     * 查询多条数据
     *
     * @param userId  用户ID
     * @param account 查询条数
     * @return 对象列表
     */
    @Override
    public PageWrapper<Account> list(Integer userId, Account account) {
        PageHelper.startPage(account.getPageNum(), account.getPageSize());
        account.setFlag(DataEnum.FLAG_STATUS_VALID.getCode());
        PageInfo<Account> page = new PageInfo<>(accountMapper.select(account));
        PageHelper.clearPage();
        return new PageWrapper<>(page);
    }

    @Override
    public void start(int rateType) {
        // 获取账号列表
        List<Account> accounts = list(rateType);

        // 获取HttpServletRequest请求对象
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String myIp = IpUtil.getIpAddr(request);
        String actual = "";

        HttpClient httpClient = HttpClients.createDefault();
        // 获取局域网IP
        String myIpResult = "";
        String region = "";
        String city = "";
        String isp = "";
        try {
            // 设置url参数 (可选)
            HttpGet httpGet = new HttpGet("https://extreme-ip-lookup.com/json/");

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            if (httpEntity != null) {
                myIpResult = EntityUtils.toString(httpEntity, "utf-8");

            }
            actual = JSONObject.parseObject(myIpResult).get("query").toString();
            region = JSONObject.parseObject(myIpResult).get("region").toString();
            city = JSONObject.parseObject(myIpResult).get("city").toString();
            isp = JSONObject.parseObject(myIpResult).get("isp").toString();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 获取地址列表

        System.err.println();
        System.err.println();
        System.err.println();
        System.err.println("~~~欢迎使用嘉哥刷票助手~~~");
        System.err.println("~~~欢迎使用嘉哥刷票助手~~~");
        System.err.println("~~~欢迎使用嘉哥刷票助手~~~");
        System.err.println();
        System.err.println();
        System.err.println();
        System.err.println("说明如下：");
        System.err.println("当前批次账号合计" + accounts.size() + "个");
        System.err.println("当前批次账号所用IP地址合计" + accounts.size() + "个");

//        System.err.println("当前批次账号所用IP地址合计" +  + "个");
        System.err.println("当前跑号设备局域网IP地址为【" + myIp + "】");
        System.err.println("当前跑号设备宽带IP地址为【" + actual + "】");
        System.err.println("当前跑号设备宽带ISP信息为【" + IpAddressUtils.getAddresses(actual) +  "】");


        for (int i = 0; i < accounts.size(); i++) {
            System.err.println();
            System.err.println();
            System.err.println();
            System.err.println();
            System.err.println("======================================账号合计" + accounts.size() + "个，第【" + (i + 1) + "】个账号====投票开始====================================================");

            System.err.println("获取代理ip");
            Map<String, String> map = getProxyUrl();

            System.err.println(JSONObject.toJSON(map));
            Map<String, String> newProxyMap = testProxyIp(map);

            // 测试代理IP
//            Map<String, String> newProxyMap = Maps.newHashMap();
//            newProxyMap.put("ip", "119.5.181.82");
//            newProxyMap.put("port", "4558");
//            testProxyIp(newProxyMap);

            start(accounts.get(i), newProxyMap);
        }
        System.err.println("======================================账号合计" + accounts.size() + "个，投票失败【" + ERROR_COUNT + "】个账号==具体原因【未绑定手机号】==投票结束====================================================");
        System.err.println("======================================账号合计" + accounts.size() + "个，投票成功【" + SUCCESS_COUNT + "】个账号==具体原因【未绑定手机号】==投票结束====================================================");
        System.err.println();
        System.err.println();
        System.err.println();
        System.err.println();
    }

    /**
     * 测试代理ip
     * @param map
     */
    private Map<String, String> testProxyIp(Map<String, String> map) {

        System.err.println(JSONObject.toJSON(map));
        String proxyIp = map.get("ip");
        String proxyPort = map.get("port");
        String proxyResult ="";
        Map<String, String> newProxyMap = null;
        try {
            // 设置url参数 (可选)
            HttpGet httpGet = new HttpGet("https://extreme-ip-lookup.com/json/");
            proxyResult = doRequest(httpGet, proxyIp, Integer.valueOf(proxyPort));
            if(proxyResult.contains("Authentication failed!")){
                System.err.println("代理IP使用无权限使用，无效IP【" + proxyIp + "】！！！，尝试再次重新提取，尝试~~~");
                proxyResult = proxyResult.replace(" Authentication failed!", "");
                proxyResult = proxyResult.replace("IP:", "");
                proxyResult = proxyResult.replace("\n", "");
                System.err.println("重新添加IP到白名单【" + proxyResult);

                newProxyMap = addWhitelistIp(proxyResult);

                // 再次测试代理IP
                System.err.println("newProxyMap===>");
                System.err.println(JSONObject.toJSON(newProxyMap));
                newProxyMap = testProxyIp(newProxyMap);
            } else {
                newProxyMap = map;
                System.err.println("当前代理IP地址为【" + proxyIp + "】");
                System.err.println("当前代理IP宽带ISP信息为【" + IpAddressUtils.getAddresses(proxyIp) +  "】");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return newProxyMap;
    }

    /**
     * 获取代理IP
     * @return
     */
    private Map<String, String> getProxyUrl() {

        // 代理IP
//      String getProxyUrl = "http://d.jghttp.alicloudecs.com/getip?num=1&type=1&pro=0&city=0&yys=0&port=1&time=1&ts=0&ys=0&cs=0&lb=1&sb=0&pb=4&mr=1&regions=";
        String getProxyUrl = "http://d.jghttp.alicloudecs.com/getip?num=1&type=1&pro=0&city=0&yys=0&port=1&time=1&ts=0&ys=0&cs=0&lb=1&sb=0&pb=4&mr=1&regions=110000,310000,370000,440000,500000,510000";

        Map map = null;
        try {

            // 获取getProxyIp
            HttpGet httpGet = new HttpGet(getProxyUrl);
            String getProxyUrlResult = ClientProxyHttpClientHttp.doRequest(httpGet);

            // 获取成功
            if (getProxyUrlResult.split(":").length == 2){
                String [] proxyArray = getProxyUrlResult.split(":");
                map = Maps.newHashMap();
                map.put("ip", proxyArray[0]);
                map.put("port", proxyArray[1].substring(0, 4));
                System.err.println("提取代理IP成功 === " + proxyArray[0]);
                System.err.println("提取代理端口成功 === " + proxyArray[1]);
            //  添加白名单
            } else if(Objects.equals(JSONObject.parseObject(getProxyUrlResult).get("code").toString(), "113")){

                String whitelistIp = JSONObject.parseObject(getProxyUrlResult).get("msg").toString().replace("请添加白名单", "");
                addWhitelistIp(whitelistIp);
            } else if(Objects.equals(JSONObject.parseObject(getProxyUrlResult).get("code").toString(), "111")){

                System.err.println("提取代理ip过于频繁，程序等待2秒...");
                TimeUnit.SECONDS.sleep(3);//秒
                System.err.println("等待结束再次提取代理ip~~~");
                map = getProxyUrl();
            } else {
                System.err.println("获取代理第三种情况");
                System.err.println(getProxyUrlResult);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    /**
     * 添加白名单
     * @param whitelistIp
     */
    private Map<String, String> addWhitelistIp(String whitelistIp) {

        String addWhitelistUrl = "http://webapi.jghttp.alicloudecs.com/index/index/save_white?neek=30978&appkey=6fdc78682a10be49bee1a7ddf6cdc468&white=" + whitelistIp;

        Map<String, String>  authenticationMap = null;
        try {

            // 获取getProxyIp
            HttpGet httpGet = new HttpGet(addWhitelistUrl);
            String addWhitelistResult = ClientProxyHttpClientHttp.doRequest(httpGet);

            if(Objects.equals(JSONObject.parseObject(addWhitelistResult).get("code").toString(), "0")){

                // 添加白名单，再次获取代理ip
                System.err.println("添加白名单，再次获取代理ip");
                authenticationMap = getProxyUrl();
            } else if(Objects.equals(JSONObject.parseObject(addWhitelistResult).get("code").toString(), "115")) {
                // 白名单已经存在，再次获取代理ip
                System.err.println("白名单已经存在，再次获取代理ip");
                authenticationMap = getProxyUrl();
            } else {
                // 添加白名单失败，再次添加白名单
                System.err.println("添加白名单失败，再次添加白名单");
                addWhitelistIp(whitelistIp);
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("~~~ 添加白名单异常 ~~~");
        }
        return authenticationMap;
    }

    @Override
    public void start(Account account, Map<String, String> proxyMap) {
        // 第一步 combine
        Map map = combine(proxyMap);

        // 第二部 geetest
        String validate = GeetestRecognition.recognition(map.get("gt").toString(), "https://passport.bilibili.com/login", map.get("challenge").toString());
        // 重新校验验证码 5 次
        for (int i = 0; i < 5; i++) {
            if (validate == null) {
                System.err.println("重新校验验证码次数" + i + 1);
                map = combine(proxyMap);
                validate = GeetestRecognition.recognition(map.get("gt").toString(), "https://passport.bilibili.com/login", map.get("challenge").toString());
            } else {
                break;
            }
        }

//        String username = "18010612141";
//        String pwd = "zyscxfsc423h";
        String username = account.getAccount();
        String pwd = account.getPassword();

        // 第三步 加密key
        Map<String, String> mapKey = getkey(proxyMap);

        // 第四步 加密pwd(替换字符串中的：autoit_key autoit_hash autoit_e)
        String passWord = ScriptEngineTest(mapKey.get("key"), mapKey.get("hash"), pwd);
        try {

            passWord = URLEncoder.encode(passWord, "utf-8");

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String url = "https://passport.bilibili.com/web/login/v2";

        String data = "captchaType=6&username=" + username + "&password=" + passWord + "&keep=true&key=" + map.get("key") + "&goUrl=&challenge=" + map.get("challenge") + "&validate=" + validate + "&seccode=" + validate + "%7Cjordan";

        String result = "";
        try {
            // 要访问的目标页面
            HttpPost httpPost = new HttpPost(url);
            // 封装对象
            StringEntity stringEntity = new StringEntity(data, "utf-8");
            // 绑定对象
            // 设置表单参数
            httpPost.setEntity(stringEntity);
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
            httpPost.setHeader("User-Agent", UA1);

            result = doRequest(httpPost, proxyMap.get("ip"), Integer.valueOf(proxyMap.get("port")));
//            System.out.println(" ---> " + result);
        } catch (Exception e) {
            e.printStackTrace();
        }



        /*
        // 创建链接
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 封装对象
        StringEntity stringEntity = new StringEntity(data, "utf-8");
        // 创建请求方式
        HttpPost httpPost = new HttpPost(url);
        // 绑定对象
        httpPost.setEntity(stringEntity);

        HttpResponse httpResponse = null;
        String result = "";

        try {
            httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();

            if (httpEntity != null) {
                result = EntityUtils.toString(httpEntity, "utf-8");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }*/

        JSONObject jsonObject = JSONObject.parseObject(result);
        String code = jsonObject.get("code").toString();

        if (Objects.equals(code, "0")) {
            String dataResult = jsonObject.get("data").toString();
            JSONObject redirectUrl = JSONObject.parseObject(dataResult);
            String redirectUrlValue = redirectUrl.get("redirectUrl").toString();

            // 封装cookie
            System.err.println("=========================================账号【" + username + "】登陆成功=============================================");
            PackageCookie(redirectUrlValue, proxyMap);
        } else if (Objects.equals(code, "-2110")) {
            System.err.println("=============账号【" + username + "】在代理IP：【" + proxyMap.get("ip") + "】登陆失败，错误代码【-2110】，该账号官方要求绑定使用手机号登录=============");
            ERROR_COUNT +=1;
        }else  {
            System.err.println("登陆失败" + jsonObject.get("message"));
        }
    }

    private Map getkey(Map<String, String> map) {

        String url = "https://passport.bilibili.com/login?act=getkey&r=" + Math.random();

        // 是否使用代理
        String result = "";
        try {
            // 设置url参数 (可选)
            HttpGet httpGet = new HttpGet( url);
            httpGet.setHeader("Referer", "https://passport.bilibili.com/login");
            httpGet.setHeader("User-Agent", UA1);
            result = doRequest(httpGet, map.get("ip"), Integer.valueOf(map.get("port")));
//            System.out.println("代理get请求 ---> " + result);
        } catch (Exception e) {
            e.printStackTrace();
        }

        JSONObject jsonObject = JSONObject.parseObject(result);
        Map<String, String> set = Maps.newHashMap();
        set.put("hash", jsonObject.get("hash").toString());
        set.put("key", jsonObject.get("key").toString());
        return set;
    }

    /**
     * 直接调用js代码
     */
    public String ScriptEngineTest(String key, String hash, String pwd) {

        // 第一步：因为是 使用chromediver所以 需要先安装chrome浏览器,
        // FIXME https://npm.taobao.org/mirrors/chromedriver/ 找到对应的版本
        // FIXME 设置环境变量

        // FIXME 第二步：设置环境变量
        System.setProperty("webdriver.chrome.driver", "E:\\JAVA_llq\\chromedriver_win32\\chromedriver.exe");

        ChromeDriver webDriver = new ChromeDriver();

        long start = System.currentTimeMillis();

        // 第三步：设置访问地址
        //----
        // 这里和浏览器 地址栏目 可以输入的 地址一样 支持 远程地址 和 本地地址
        //webDriver.get("http://www.51jdy.cn");
        //webDriver.get("http://localhost:8080/web/Noname2.html?pwd=98912&username=halou");

        String url = "http://118.126.111.189/getJsencryptPwd.html?&hash=" + hash + "&key=" + key + "&pwd=" + pwd;
        webDriver.get(url);


        // 第四步：获取输出信息；html中的js代码执行后 在body中document.write()或者 赋值给body或者div
        // 元素定位 获取 <html> 中<body> 下面的 内容
        WebElement webElement = webDriver.findElement(By.xpath("/html/body"));
        String result = webElement.getText();
//        System.out.println(result);
        // System.out.println("耗时：" + (System.currentTimeMillis() - start));
        //  等待5秒后自动关闭浏览器
        try {
            Thread.sleep(1000);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        //关闭浏览器窗口
        webDriver.quit();
        return result;
    }

    /**
     * 结合 gee test
     */
    private Map combine(Map<String, String> map) {

        String url = "https://passport.bilibili.com/web/captcha/combine?plat=6";

        String result = "";
        try {
            // 设置url参数 (可选)
            HttpGet httpGet = new HttpGet(url);
            httpGet.setHeader("Referer", "https://passport.bilibili.com/login");
            httpGet.setHeader("User-Agent", UA1);
            result = doRequest(httpGet, map.get("ip"), Integer.valueOf(map.get("port")));
//            System.out.println("代理get请求 ---> " + result);
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.err.println(result);
        JSONObject jo = JSONObject.parseObject(result);
        JSONObject jos = JSONObject.parseObject(jo.get("data").toString());
        JSONObject j = JSONObject.parseObject(jos.get("result").toString());
//        System.err.println(j);
//        System.err.println(j.get("key"));
//        System.err.println(j.get("challenge"));

        Map<String, String> set = Maps.newHashMap();
        set.put("key", j.get("key").toString());
        set.put("challenge", j.get("challenge").toString());
        set.put("gt", j.get("gt").toString());

        return set;
    }

    public static void main(String[] args) {
        AccountServiceImpl asi = new AccountServiceImpl();
//        asi.ScriptEngineTest();
//        asi.start();

    }

    /**
     * 封装cookie
     */
    public void PackageCookie(String redirectUrl, Map<String, String> proxyMap) {

        String url = "https://api.bilibili.com/x/activity/selection/vote";

        String cookie = redirectUrl.replace("https://passport.biligame.com/crossDomain?", "");
        cookie = cookie.replace("gourl=https%3A%2F%2Fwww.bilibili.com", "");
        cookie = cookie.replace("Expires=15551000&", "");
        String headerCookie = cookie.replace("&", ";");

//        String dataResult = "https://passport.biligame.com/crossDomain?DedeUserID=100025121&DedeUserID__ckMd5=9efe8f3b10b4672c&Expires=15551000&SESSDATA=6dd7d506%2C1623293861%2Cfdc38%2Ac1&bili_jct=78173252843e3c2d7af8415e78fcb974&gourl=https%3A%2F%2Fwww.bilibili.com";

        // 检查字符串是否包含指定的子串.
        // 拆分字符串为若干子串.
        // csrf=78173252843e3c2d7af8415e78fcb974
        String[] c = headerCookie.split(";");
        String dataResultCookie = c[c.length - 1].replace("bili_jct=", "csrf=");
        dataResultCookie= dataResultCookie + "&category_id=3&productrole_id=589&ua=Mozilla%2F5.0%20%28Windows%20NT%2010.0%3B%20Win64%3B%20x64%29%20AppleWebKit%2F537.36%20%28KHTML%2C%20like%20Gecko%29%20Chrome%2F86.0.4240.198%20Safari%2F537.36&platform=web&buvid=";

        sendPost(url, dataResultCookie, headerCookie, proxyMap);
    }

    public void sendPost(String url, String data, String cookie, Map<String, String> proxyMap){

        String result = "";
        try {
            // 要访问的目标页面
            HttpPost httpPost = new HttpPost(url);
            // 封装数据
            StringEntity stringEntity = new StringEntity(data, "utf-8");
            // 绑定数据
            httpPost.setEntity(stringEntity);
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
            httpPost.setHeader("User-Agent", UA1);
            // 设置cookie
            httpPost.setHeader("Cookie", cookie);

            result = doRequest(httpPost, proxyMap.get("ip"), Integer.valueOf(proxyMap.get("port")));
//            System.out.println(" ---> " + result);
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.err.println("                             " + result);
        System.err.println("==========================代理IP【" + proxyMap.get("ip") + "】==================投票结束====================================================");
        SUCCESS_COUNT +=1;
    }


    private void login(String account, String pwd) {
        String url = "https://passport.bilibili.com/web/login/v2";
    }
/*
    private String findHtml(String key, String hash, String pwd) {
        key = key.replaceAll(" ", "%20");
        key = key.replaceAll("\n", "\\n");
        String url = "http://127.0.0.1/getJsencryptPwd.html?&hash=" + hash + "&key=" + key + "&ip=127.0.0.1";

        HttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        String result = "";
        HttpResponse httpResponse = null;
        try {

            httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            System.out.println("httpResponse=" + httpResponse);
            System.err.println("httpEntity=" + httpEntity);
            if (httpEntity != null) {
                result = EntityUtils.toString(httpEntity, "utf-8");

            }

        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println("result=" + result);
        return null;
    }*/

    class MyCookieSpec extends DefaultCookieSpec {
        @Override
        public List<Cookie> parse(Header header, CookieOrigin cookieOrigin) throws MalformedCookieException {
            String value = header.getValue();
            String prefix = "Expires=";
            if (value.contains(prefix)) {
                String expires = value.substring(value.indexOf(prefix) + prefix.length());
                expires = expires.substring(0, expires.indexOf(";"));
                String date = DateUtils.formatDate(new Date(Long.parseLong(expires) * 1000L),"EEE, dd-MMM-yy HH:mm:ss z");
                value = value.replaceAll(prefix + "\\d{10};", prefix + date + ";");
            }
            header = new BasicHeader(header.getName(), value);
            return super.parse(header, cookieOrigin);
        }
    }

    /**
     *
     * @param type
     * @return
     */
    private List<Account> list(int type) {
        Account account = new Account();
        account.setFlag(type);
        return accountMapper.select(account);
    }

    /**
     * 执行请求
     *
     * @param httpReq
     * @return
     */
    public String doRequest(HttpRequestBase httpReq, String proxyIp, int proxyPort) {

        String result = "";
        // 代理
        HttpHost proxy = new HttpHost(proxyIp, proxyPort, "http");

        // 设置请求参数
        RequestConfig reqConfig = RequestConfig.custom()
                .setProxy(proxy)
                .setConnectionRequestTimeout(3000)
                .setConnectTimeout(3000)
                .setSocketTimeout(3000)
                .build();

        httpReq.setConfig(reqConfig);

        try {
            // 设置请求头
//            setHeaders(httpReq);

            CloseableHttpClient httpClient = HttpClients.createDefault();
            // 执行请求
            CloseableHttpResponse httpResp = httpClient.execute(httpReq);

            // 获取http code

            int statusCode = httpResp.getStatusLine().getStatusCode();
//            System.out.println("响应码 ---> " + statusCode);

            HttpEntity entity = httpResp.getEntity();
            if (entity != null) {
                result = EntityUtils.toString(entity, "utf-8");
            }

            httpResp.close();
            httpClient.close();
            httpReq.abort();
        } catch (NoHttpResponseException e) {
//            e.printStackTrace();
            System.err.println("该代理【无法响应】，再次尝试~~~");
            return doRequest(httpReq, proxyIp, proxyPort);
        } catch (HttpHostConnectException e) {
//            e.printStackTrace();
            System.err.println("该代理【连接被拒绝】，再次尝试~~~");
            return doRequest(httpReq, proxyIp, proxyPort);
        } catch (SocketTimeoutException e) {
//            e.printStackTrace();
            System.err.println("该代理【读取】超时，再次尝试~~~");
            return doRequest(httpReq, proxyIp, proxyPort);
        } catch (ConnectTimeoutException e) {
//            e.printStackTrace();
            System.err.println("该代理【连接】超时，再次尝试~~~");
            return doRequest(httpReq, proxyIp, proxyPort);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return result;
    }
}